<template>
  <div style="background-color: #f6f6f6">
    <el-row>
      <el-col :span="20" :offset="2">
        <div class="form" style="padding-left: 20px;">
          <el-form :inline="true" :model="search" class="dw-form-inline" size="medium">
            <el-form-item label="租户名">
              <el-input v-model="search.key" placeholder="请输入要查询的租户名" clearable></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;">
              <el-button type="primary" icon="el-icon-search" @click="queryTenants(search.key)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <div class="table-title">
            <el-row :span="24" type="flex" justify="space-between" align="middle">
              <el-col :span="4"><h3>租户管理</h3></el-col>
              <el-col :span="20" style="text-align: right;">
                <el-button type="primary" size="medium" icon="el-icon-plus" plain @click="handleAdd()">新增</el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%"
                    border :default-sort="{prop: 'username', order: 'ascending'}" @sort-change="handleSortChange" :header-cell-class-name="handleHeadAddClass">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="租户id" prop="id" align="center" v-if="false"></el-table-column>
            <el-table-column label="序号" type="index" width="60" align="center">
              <template v-slot="scope">
                <span>{{ (currentPage - 1) * pageSize + 1 + scope.$index }}</span>
              </template>
            </el-table-column>
            <el-table-column label="租户名" prop="username" sortable="custom" align="center"></el-table-column>
            <!--            <el-table-column label="密码" prop="password" align="center" v-if="false"></el-table-column>-->
            <el-table-column label="租户电话" prop="telnumber" align="center"></el-table-column>
            <el-table-column label="密保问题" prop="securityQuestionContext" align="center"
                             v-if="false"></el-table-column>
            <el-table-column label="密保回答" prop="securityQuestionAnswer" align="center"
                             v-if="false"></el-table-column>
            <el-table-column label="创建时间" prop="createdDate" sortable="custom" width="150" align="center">
              <template v-slot="scope">
                <i class="el-icon-time"></i>
                {{ formatDate(scope.row.createdDate) }}
              </template>
            </el-table-column>
            <el-table-column label="最后登录时间" prop="lastLoginDate" sortable="custom" width="150" align="center">
              <template v-slot="scope">
                <i class="el-icon-time"></i>
                {{ formatDate(scope.row.lastLoginDate) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="100" align="center">
              <template v-slot="scope">
                <el-tag :type="getTagType(scope.row.status)">
                  <!-- 插值表达式支持函数执行 并且渲染的是函数的return值 -->
                  {{ formatStatus(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="未结费用" prop="costNow" sortable="custom" width="120" align="center"></el-table-column>
            <el-table-column label="已结费用" prop="historyCost" sortable="custom" width="120" align="center"></el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template v-slot="scope">
                <el-tooltip content="编辑租户信息" effect="dark" placement="top">
                  <el-button size="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除租户" effect="dark" placement="top">
                  <el-button size="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>

    <div>
      <el-dialog :title="dialogTitle" :visible="dialogFormVisible" append-to-body width="40%"
                 :close-on-click-modal="false" @close="handleClose()">
        <el-form ref="tenantForm" :model="tenantForm" :rules="tenantFormRules" status-icon label-position="top">
          <el-form-item :label-width="formLabelWidth" label="租户id" prop="id" style="margin-top: 0px;" v-if="false">
            <el-input v-model="tenantForm.id" autocomplete="off" placeholder="请输入id" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="租户名" prop="username" style="margin-top: 0px;">
            <el-input v-model="tenantForm.username" autocomplete="off" placeholder="请输入租户名"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密码" prop="password" class="dw-dialog-form-item"
                        v-if="this.dialogTitle=='创建租户'">
            <el-input v-model="tenantForm.password" autocomplete="off" placeholder="请输入密码"
                      show-password></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="确认密码" prop="checkPassword" class="dw-dialog-form-item"
                        v-if="this.dialogTitle=='创建租户'">
            <el-input v-model="tenantForm.checkPassword" autocomplete="off" placeholder="请再次输入密码"
                      show-password></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="手机号" prop="telnumber" class="dw-dialog-form-item">
            <el-input v-model="tenantForm.telnumber" autocomplete="off" placeholder="请输入手机号"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密保问题" prop="securityQuestionContext"
                        class="dw-dialog-form-item">
            <el-input v-model="tenantForm.securityQuestionContext" autocomplete="off" placeholder="请输入密保问题"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密保回答" prop="securityQuestionAnswer"
                        class="dw-dialog-form-item">
            <el-input v-model="tenantForm.securityQuestionAnswer" autocomplete="off" placeholder="请输入密保回答"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="账号状态" prop="status" class="dw-dialog-form-item">
            <el-radio-group v-model="tenantForm.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">冻结</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="未结费用" prop="costNow" class="dw-dialog-form-item"
                        v-if="false">
            <el-input v-model="tenantForm.costNow" autocomplete="off" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="已结费用" prop="historyCost" class="dw-dialog-form-item"
                        v-if="false">
            <el-input v-model="tenantForm.historyCost" autocomplete="off" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="删除标志" prop="delFlag" class="dw-dialog-form-item"
                        v-if="false">
            <el-input v-model="tenantForm.delFlag" autocomplete="off" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button type="primary" @click="handleConfirm()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {createTenant, modifyTenantInfo, queryTenantList, queryTenantsByKey, removeTenantByName} from "../../api/admin";
import {compare, DateFormat} from "../../utils/common.js";

export default {
  name: "adminHome",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.tenantForm.checkPassword !== '') {
          this.$refs['tenantForm'].validateField('checkPassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.tenantForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      // change: false,
      search: {
        key: null
      },
      tableData: [],
      pageSize: 5,
      currentPage: 1,
      total: 0,
      formInline: {
        loginName: null,
        status: null
      },
      dialogTitle: '创建租户',
      dialogFormVisible: false,
      tenantForm: {
        id: '',
        username: '',
        password: '',
        checkPassword: '',
        telnumber: '',
        securityQuestionContext: '',
        securityQuestionAnswer: '',
        createdDate: '',
        lastLoginDate: '',
        status: '',
        costNow: 0,
        historyCost: 0,
        delFlag: ''
      },
      tenantFormRules: {
        username: [
          {required: true, message: '请输入租户名', trigger: 'blur'},
          {min: 1, max: 18, message: '长度在 1 到 18 个字符', trigger: 'blur'},
          // {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
          {validator: validatePass2, trigger: 'blur', required: true}
        ],
        telnumber: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {
            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: "请输入合法手机号",
            trigger: "blur"
          }
        ],
        securityQuestionContext: [
          {required: true, message: '请输入密保问题', trigger: 'blur'},
          {min: 4, max: 64, message: '长度在 4 到 64 个字符', trigger: 'blur'}
        ],
        securityQuestionAnswer: [
          {required: true, message: '请输入密保回答', trigger: 'blur'},
          {min: 4, max: 64, message: '长度在 4 到 64 个字符', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择账号状态', trigger: 'change'}
        ],
        costNow: [
          {required: true, message: '请输入未结费用', trigger: 'blur'},
          {type: 'number', message: '未结费用必须为数字', trigger: 'blur'}
        ],
        historyCost: [
          {required: true, message: '请输入已结费用', trigger: 'blur'},
          {type: 'number', message: '已结费用必须为数字', trigger: 'blur'}
        ]
      },
      formLabelWidth: '120px',

    }
  },
  methods: {
    showAllTenants() {
      queryTenantList().then((response) => {
        this.tableData = response.data.data
        this.handleSortChange({prop: 'username', order: 'ascending'})
        // console.log(response.data.data)
        this.total = response.data.data.length
        // this.$forceUpdate()
      })
    },
    queryTenants(key) {
      queryTenantsByKey(key).then((response) => {
        console.log(key)
        console.log(response.data)
        this.tableData = response.data.data
        this.handleSortChange({prop: 'username', order: 'ascending'})
        this.total = response.data.data.length
      })
    },
    handleAdd() {
      this.clearForm()
      this.dialogTitle = '创建租户'
      this.tenantForm.status = 0
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.clearForm()
      this.dialogTitle = '修改租户信息'
      for (let key in row) {
        // console.log(key + ": " +row[key])
        this.tenantForm[key] = row[key]
      }
      this.tenantForm.status = parseInt(row.status)
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$msgbox.confirm('确认删除此用户吗？', '删除警告', {
        type: 'warning',
        confirmButtonText: '确认删除'
      }).then(() => {
        removeTenantByName(row.username).then((response) => {
          if (response.data.code == '200') {
            this.$message.success(response.data.message)
            this.showAllTenants()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {
      })
    },
    // dataInit () {
    //   let num = 15
    //   for (let i = 0; i<num; i++){
    //     this.tableData[i] = {username:"测试用租户"+i};
    //   }
    //   this.total = num
    //   this.pageSize = 10
    //   this.currentPage = 1
    // }
    handleClose() {
      this.clearForm()
      this.dialogFormVisible = false
    },
    handleConfirm() {
      this.$refs['tenantForm'].validate((valid) => {
        if (valid) {
          let {
            id, username, password, telnumber, securityQuestionContext,
            securityQuestionAnswer, createdDate, lastLoginDate,
            status, costNow, historyCost, delFlag
          } = this.tenantForm
          if (this.dialogTitle == '创建租户') {
            let submitData = {
              username, password, telnumber, securityQuestionContext,
              securityQuestionAnswer, status
            }
            createTenant(submitData).then((response) => {
              if (response.data.code == '200') {
                this.$message.success(response.data.message)
                this.showAllTenants()
                this.dialogFormVisible = false
              } else {
                this.$message.error(response.data.message)
              }
            })
            // console.log(submitData)
          } else if (this.dialogTitle == '修改租户信息') {
            let submitData = {
              id, username, telnumber, securityQuestionContext,
              securityQuestionAnswer, createdDate,
              status
            }
            modifyTenantInfo(submitData).then((response) => {
              if (response.data.code == '200') {
                this.$message.success(response.data.message)
                this.showAllTenants()
                this.dialogFormVisible = false
              } else {
                this.$message.error(response.data.message)
              }
            })
          }
        }
      })
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
    },
    formatStatus(type) {
      // 根据源数据经过处理 把处理之后的数据返回
      // 定义一个映射结构
      const map = {
        0: '正常',
        1: '冻结'
      }
      return map[type]
    },
    getTagType(type) {
      const map = {
        0: 'success',
        1: 'danger'
      }
      return map[type]
    },
    formatDate(date) {
      return DateFormat(date)
    },
    clearForm() {
      for (let key in this.tenantForm) {
        this.tenantForm[key] = ''
      }
    },
    handleSortChange({prop, order}){
      this.tableData.sort(compare(prop, order))
    },
    handleHeadAddClass({column}){
      if(this.tableData[column.property]){
        column.order = this.tableData[column.property];
      }
    }
  },
  created() {
    this.showAllTenants()
  }
}
</script>

<style scoped>
.form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.table {
  background: white;
  padding: 20px;
}

.table.table-title {
  padding-bottom: 20px;
  border-bottom: 1px solid #f3f3f3;
}

.dw-table.dw-table-title h3 {
  padding: 0px;
  margin: 0px;
}

.el-form-item {
  margin-bottom: 0px;
}

.dw-dialog-form-item {
  margin-top: 20px;
}

.pagination {
  padding-top: 20px;
  text-align: right;
}
</style>
